package com.sam.im.heiqun.pay;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.nets.PGApi;
import com.sam.im.heiqun.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.opensdk.utils.ILog;
import com.yuyh.library.utils.data.safe.MD5;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import java.util.List;

/**
 * 微信支付接口
 * Created by zhangqiang on 2016/5/25.
 */
public class WXPay {

    private static final String APP_ID = PGApi.WX_APP_ID;

    private static IWXAPI wxApi;

    static {

        wxApi = WXAPIFactory.createWXAPI(App.getInstance(), APP_ID);
        wxApi.setLogImpl(new ILog() {
            @Override
            public void v(String s, String s1) {
                WXPayEntryActivity.saveToFile(s + "--v-" + s1);
            }

            @Override
            public void d(String s, String s1) {
                WXPayEntryActivity.saveToFile(s + "--d-" + s1);
            }

            @Override
            public void i(String s, String s1) {
                WXPayEntryActivity.saveToFile(s + "--i-" + s1);
            }

            @Override
            public void w(String s, String s1) {
                WXPayEntryActivity.saveToFile(s + "--w-" + s1);
            }

            @Override
            public void e(String s, String s1) {
                WXPayEntryActivity.saveToFile(s + "--e-" + s1);
            }
        });
        wxApi.registerApp(APP_ID);
    }

    /**
     * 是否支持微信支付
     *
     * @return
     */
    public static boolean isPaySupport() {

        return wxApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
    }

    /**
     * 请求支付
     *
     * @param partnerId 微信支付分配的商户号
     * @param prepayId  微信返回的支付交易会话ID
     * @param nonceStr  随机字符串，不长于32位。推荐随机数生成算法
     * @param timeStamp 时间戳
     * @param sign      签名
     */
    public static void requestPay(String partnerId, String prepayId, String nonceStr, String timeStamp, String sign) {

        if (TextUtils.isEmpty(partnerId) || TextUtils.isEmpty(prepayId) || TextUtils.isEmpty(nonceStr) ||
                TextUtils.isEmpty(timeStamp) ||
                TextUtils.isEmpty(sign)) {
            return;
        }

        PayReq req = new PayReq();
        //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
        req.appId = APP_ID;
        req.partnerId = partnerId;
        req.prepayId = prepayId;
        req.nonceStr = nonceStr;
        req.timeStamp = timeStamp;
        req.packageValue = "Sign=WXPay";
        req.sign = sign;
        req.extData = "app data"; // optional

        WXPayEntryActivity.saveToFile("----------发起支付-----------\n");
        WXPayEntryActivity.saveToFile(JSON.toJSON(req).toString());
        WXPayEntryActivity.saveToFile("----------------------------\n");

        //对sign 二次赋值
        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
        req.sign = genAppSign(signParams);

        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        wxApi.sendReq(req);
    }

    private static String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append("1121212sdfafadfdasfasg1212121212");
//        sb.append("sign str\n" + sb.toString() + "\n\n");
        return stringMD5(sb.toString()).toLowerCase();
    }

    interface NameValuePair {

        String getName();

        String getValue();
    }

   static class BasicNameValuePair implements NameValuePair {

        private String name;

        private String value;

        public BasicNameValuePair(String name, String value) {
            this.name = name;
            this.value = value;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getValue() {
            return value;
        }
    }

    public static String stringMD5(String input) {

        try {

            // 拿到一个MD5转换器（如果想要SHA1参数换成”SHA1”）

            MessageDigest messageDigest =MessageDigest.getInstance("MD5");


            // 输入的字符串转换成字节数组

            byte[] inputByteArray = input.getBytes();



            // inputByteArray是输入字符串转换得到的字节数组

            messageDigest.update(inputByteArray);



            // 转换并返回结果，也是字节数组，包含16个元素

            byte[] resultByteArray = messageDigest.digest();



            // 字符数组转换成字符串返回

            return byteArrayToHex(resultByteArray);



        } catch (NoSuchAlgorithmException e) {

            return null;

        }

    }

    public static String byteArrayToHex(byte[] byteArray) {

        // 首先初始化一个字符数组，用来存放每个16进制字符

        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };



        // new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））

        char[] resultCharArray =new char[byteArray.length * 2];



        // 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去

        int index = 0;

        for (byte b : byteArray) {

            resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];

            resultCharArray[index++] = hexDigits[b& 0xf];

        }



        // 字符数组组合成字符串返回

        return new String(resultCharArray);

    }
}

